package nsqp

import (
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/imp/enums"
	"bgs/nsqp/topic"
	"encoding/json"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

// GsmsProxy proxy gsms nsq message
type GsmsProxy struct {
	dao  *db.PgDao
	slog *zap.SugaredLogger
	pub  *nsq.Producer
}

// SmsMqBody 验证短信消息体
type SmsMqBody struct {
	// RequestID 业务幂等Id
	RequestID string `json:"request_id"`
	// Phone 手机号
	Phone string `json:"phone"`
	// AppID 分配的appId
	AppID string `json:"appid"`
	// MessageType 验证类型
	MessageType string `json:"message_type" binding:"required"`
}

// NewGsmsProxy initialization
func NewGsmsProxy(nsqConf conf.NsqSection, pgdao *db.PgDao, slog *zap.SugaredLogger) (proxy *GsmsProxy, err error) {
	config := nsq.NewConfig()
	producer, err := nsq.NewProducer(nsqConf.NsqdAddress, config)
	if err != nil {
		return
	}
	proxy = &GsmsProxy{
		dao:  pgdao,
		slog: slog,
		pub:  producer,
	}

	return
}

// SendVerifyCode 发送验证短信
func (gsms *GsmsProxy) SendVerifyCode(requestID, phone, messageType string) (err error) {
	gsms.slog.Infof("SendVerifyCode to %s of %s", phone, messageType)
	body, err := json.Marshal(SmsMqBody{
		RequestID:   requestID,
		Phone:       phone,
		AppID:       string(enums.AppIDBGAPI),
		MessageType: messageType,
	})
	if err != nil {
		gsms.slog.Errorf("json marshal err:%v", err)
		return
	}
	err = gsms.pub.Publish(topic.SendSMS, body)
	if err != nil {
		gsms.slog.Errorf("nsq publish err:%v", err)
		return
	}
	return
}
